Ext.namespace("Sdp.CompaniesGrid");

Sdp.CompaniesGrid = Ext.extend(Ext.app.Module, {
	id : 'companies-grid',

	init : function(){
		this.launcher = {
			text: 'Companies',
			iconCls:'bogus',
			handler : this.createWindow,
			scope: this
		}
	},

	getDataSource : function() {
		var ds = new Ext.data.Store({
			proxy: new Ext.data.HttpProxy({
				url: 'index.php?m=companies&a=do_search&suppressHeaders=1',
				method: 'POST'
		    }),
		    baseParams:{
		    	c: "ledger",
		    	k: "search",
		    },

			reader: new Ext.data.JsonReader({
	            root: 'rows',
	            totalProperty: 'totalRows',
	        },
	            Ext.data.Record.create([
		            {name: 'company_id'},
		            {name: 'company_code'},
		            {name: 'company_exact_code'},
		            {name: 'company_name'},
		            {name: 'company_address1'},
		            {name: 'company_phone1'},
		            {name: 'company_fax'},
		            {name: 'company_vat_code'},
		            {name: 'div_name'}
		        ])
        	),

			sortInfo:{field: 'company_name', direction: "ASC"},

		});
		ds.load({params: {
        	start: 0,
        	limit: 10,
        }});
		return ds;
	},

	makePaggingBar : function(ds, filters) {
		var pagging = new Ext.PagingToolbar({
			pageSize: 10,
			store: ds,
			displayInfo: true,
			displayMsg: 'Displaying customers {0} - {1} of {2}',
			emptyMsg: 'No customers to display',
			plugins: filters
		});

		return pagging;
	},

	buildGridFilter : function() {
		Ext.ux.menu.RangeMenu.prototype.icons = {
          gt: 'ext/img/greater_then.png',
          lt: 'ext/img/less_then.png',
          eq: 'ext/img/equals.png'
		};
		Ext.ux.grid.filter.StringFilter.prototype.icon = 'ext/img/find.png';

		var filters = new Ext.ux.grid.GridFilters({
			filters:[
				{type: 'string',  dataIndex: 'company_name'},
				{type: 'string', dataIndex: 'company_code'},
				{type: 'string', dataIndex: 'company_vat_code'},
				{type: 'string', dataIndex: 'company_exact_code'}
			],

			paramPrefix: 'company_',

			cleanParams: function(p){
				var regex = new RegExp("^" + this.paramPrefix);
				for(var key in p)
					if(regex.test(key))
						delete p[key];
			},

			buildQuery: function(filters){
                var p = {};
				for(var i=0, len=filters.length; i<len; i++){
					var f    = filters[i];
					for(var key in f.data)
						p[f.field] = f.data[key];
				}

				return p;
		    }
		});

		return filters;
	},

	buildGrid : function() {
		var sm = new Ext.grid.RowSelectionModel({singleSelect:true});

		// example of getting a reference to another module's launcher object
        var tabWinLauncher = MyDesktop.getModule('tab-win').launcher;

		var ds = this.getDataSource();

		var filters = this.buildGridFilter();

		var grid = new Ext.grid.GridPanel({
			autoExpandColumn:'company_name',
			border:false,
			ds: ds,
			cm: new Ext.grid.ColumnModel([
				new Ext.grid.RowNumberer(),
				{header: "Code", sortable: true, dataIndex: 'company_code'},
				{header: "Exact Code", sortable: true, dataIndex: 'company_exact_code'},
				{header: "Name", sortable: true, dataIndex: 'company_name'},
				{header: "VAT Code", sortable: true, dataIndex: 'company_vat_code'},
				{header: "Address", sortable: true, dataIndex: 'company_address1'},
				{header: "Tel", sortable: true, dataIndex: 'company_phone1'},
				{header: "Fax", sortable: true, dataIndex: 'company_fax'},
			]),
			plugins: filters,
			shadow: false,
			shadowOffset: 0,
			sm: sm,
			loadMask: {msg: 'Loading'},
			tbar: [{
				text:'Add Customer',
				tooltip:'Add a new customer',
				iconCls:'icon-add'
			},'-',{
				text:'Delete Customer',
				tooltip:'Remove the selected customer',
				iconCls:'icon-remove'
			},'-',{
				// example button to open another module
				text: 'Open Tab Window',
				handler: tabWinLauncher.handler,
				scope: tabWinLauncher.scope,
				iconCls: tabWinLauncher.iconCls
			}],

			bbar: this.makePaggingBar(ds, filters),

			viewConfig: {
				forceFit:true
			}
		});

		this.buildGridAction(grid);

		return grid;
	},

	buildGridAction : function(grid) {
		// example of getting a reference to another module's launcher object
		grid.on({
			rowdblclick : this.openCompany,
        	scope: this
		});

	},

	openCompany : function(g, rowIndex, e) {
		var record = g.getSelectionModel().getSelected();
		e.stopEvent();
		var m = this.app.getModule('companies-view');
		m.createWindow(record.data);
	},

	createWindow : function(){
		var desktop = this.app.getDesktop();
		var win = desktop.getWindow('companies-grid');
		if(!win){
			var grid = this.buildGrid();
            win = desktop.createWindow({
                id: 'companies-win',
                title:'Customers grid',
                width:740,
                height:480,
                iconCls: 'companies-grid',
                shim:false,
                animCollapse:false,
                constrainHeader:true,
				layout: 'fit',
                items: grid
            });
		}
		win.show();
	}
});